package com.hh.controller;

import com.hh.item.pojo.User;
import com.hh.service.ISearchService;
import com.hh.utils.RedisKeyUtil;
import com.hh.utils.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author yangfan
 * @date 2020/7/17 15:39
 * @description
 */
@RestController("/search")
public class SearchController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private ValueOperations<String, Object> valueOperations;
    @Autowired
    private HashOperations<String, String, Object> hashOperations;
    @Autowired
    private ListOperations<String, Object> listOperations;
    @Autowired
    private SetOperations<String, Object> setOperations;
    @Autowired
    private ZSetOperations<String, Object> zSetOperations;
    @Resource
    private RedisService redisService;
    @Autowired
    private ISearchService searchService;

    @GetMapping("/init")
    public void init() {
        List<User> users = searchService.searchAll();
        String str;
        for (User user : users) {
            str = RedisKeyUtil.getKey("userIdName", user.getUserId().toString(), user.getUserName());
            if (!redisService.existsKey(str))
                valueOperations.set(str, null);

        }
    }

    @GetMapping
    public List<String> getAllIdAndName() {
        Set<String> set = stringRedisTemplate.keys("userIdName:" + "*");
        List<String> list = new ArrayList<>();
        assert set != null;
        for (String str : set) {
            list.add(str.substring(str.indexOf(":") + 1));
        }
        return list;
    }

    @GetMapping("/{username}")
    public List<String> getByName(@PathVariable String username) {
        Set<String> set = stringRedisTemplate.keys("userIdName:*:*" + username + "*");
        List<String> list = new ArrayList<>();
        assert set != null;
        for (String str : set) {
            list.add(str.substring(str.indexOf(":") + 1));
        }
        return list;
    }
}
